package com.hz.oss.controller;

import com.hz.common.utils.FileUtil;
import com.hz.common.utils.R;
import com.hz.oss.entity.CbExpandFileEntity;
import com.hz.oss.service.CbExpandFileService;
import com.hz.oss.service.CbExpandResourceService;
import com.hz.oss.service.OssService;
import com.hz.oss.entity.CbExpandResourceEntity;
import com.hz.oss.vo.FileNameAndUrl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

@RestController
@RequestMapping("/oss")
public class OssController {

    @Autowired
    private OssService ossService;

    @Autowired
    private CbExpandFileService expandFileService;

    @Autowired
    private CbExpandResourceService expandResourceService;

    @PostMapping("/upload")
    @ApiOperation("上传其他文件，图片、文件")
    public R upload(MultipartFile file){
        String url = ossService.upload(file);
        return R.ok().put("url",url).put("filename", file.getOriginalFilename()).put("size", file.getSize());
    }

    @GetMapping("/uploadZip")
    @ApiOperation("上传资源包")
    public R uploadZip(@RequestParam("path") String path){
        String url = ossService.uploadZip(path);
        return R.ok().put("url",url);
    }

    @PostMapping("/uploadPictures")
    @ApiOperation("上传多张图片")
    public R uploadPics(List<MultipartFile> filedatas) {
        List<FileNameAndUrl> urlList = new ArrayList<>();
        // 逻辑代码
        for (MultipartFile file : filedatas) {
            FileNameAndUrl url = ossService.uploads(file);
            urlList.add(url);
        }
        return R.ok().put("urlList", urlList);
    }

    @PostMapping("/uploadPicByPhoneCamera")
    @ApiOperation("手机拍摄上传图片")
    public R uploadPicByPhoneCamera(MultipartFile file){
        String url = ossService.uploadPicByPhoneCamera(file);
        return R.ok().put("url",url);
    }

    @GetMapping("/test")
    @ApiOperation("手机拍摄上传图片")
    public R test(){
        String url = "访问成功";
        System.out.println(url);
        return R.ok().put("url",url);
    }

    @Transactional
    @PostMapping("/uploadExpandResourceZip")
    @ApiOperation("上传扩展资源资源包")
    public R uploadExpandResourceZip(MultipartFile file,Integer addType,Integer expandEditionType) {
        File srcFile = multipartFileToFile(file);
        String inputFile = srcFile.getAbsolutePath();
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(new File(inputFile), Charset.forName("GBK"));
            String destDirPath = inputFile.replace(".zip", "");
            //开始解压
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                // 如果是文件夹，就创建个文件夹
                if (entry.isDirectory()) {
                    srcFile.mkdirs();
                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[1024];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }
            }
            zipFile.close();
            //解压完毕
            //获取扩展资源文件夹List
            File expandResourceDirList = new File(destDirPath);
            File[] expandResources = expandResourceDirList.listFiles();
            for (File expandResource:expandResources) {
                CbExpandResourceEntity cbExpandResource = new CbExpandResourceEntity();
                //扩展资源文件夹
                File expandResourceTxt = null;
                File expandResourceJpg = null;
                //扩展资源下的所有文件
                File[] expandSourcesFiles = expandResource.listFiles();
                for (File f:expandSourcesFiles){
                    if (!f.isDirectory()){
                        if (f.getName().lastIndexOf(".txt",f.getName().length()-4)!=-1)
                            expandResourceTxt = f;
                        else if (f.getName().lastIndexOf(".png",f.getName().length()-4)!=-1)
                            expandResourceJpg = f;
                        else if (f.getName().lastIndexOf(".jpg",f.getName().length()-4)!=-1)
                            expandResourceJpg = f;
                    }
                }
                if (expandResourceTxt == null || expandResourceJpg == null) throw new IOException();
                String resourceCover = ossService.upload(FileUtil.fileToMultipartFile(expandResourceJpg));

                //读取文本中的资源名称、资源简介、书法家简介字段
                BufferedReader bi = new BufferedReader(new FileReader(expandResourceTxt));
                String resourceName = bi.readLine();
                String resourceIntroduction = bi.readLine();
                String calligrapherIntroduction = bi.readLine();
                bi.close();

                cbExpandResource.setName(resourceName);
                cbExpandResource.setExpandEditionType(expandEditionType);
                cbExpandResource.setAddType(addType);
                cbExpandResource.setCalligrapherIntroduction(calligrapherIntroduction);
                cbExpandResource.setResourceCover(resourceCover);
                cbExpandResource.setCreatetime(new Date());
                cbExpandResource.setResourceIntroduction(resourceIntroduction);

                expandResourceService.save(cbExpandResource);

                //获取扩展文件文件夹List
                File[] expandFileDirList = expandResource.listFiles();
                int forder = 1;
                for (File expandFileDir:expandFileDirList) {
                    if (expandFileDir.isDirectory()){
                        File dir = new File(expandFileDir.getAbsolutePath());
                        File mp3 = null;
                        File file1 = null;
                        File txt = null;
                        File file2 = null;
                        File[] files = dir.listFiles();
                        for (File f:files) {
                            if (f.getName().lastIndexOf(".mp3",f.getName().length()-4)!=-1)
                                mp3 = f;
                            else if(f.getName().lastIndexOf(".pdf",f.getName().length()-4)!=-1)
                                file1 = f;
                            else if(f.getName().lastIndexOf(".mp4",f.getName().length()-4)!=-1)
                                file1 = f;
                            else if(f.getName().lastIndexOf(".jpg",f.getName().length()-4)!=-1)
                                file1 = f;
                            else if(f.getName().lastIndexOf(".png",f.getName().length()-4)!=-1)
                                file1 = f;
                            else if(f.getName().lastIndexOf(".txt",f.getName().length()-4)!=-1)
                                txt = f;
                            else if(f.getName().lastIndexOf(".ppt",f.getName().length()-4)!=-1)
                                file2 = f;
                        }
                        if (file1==null || txt==null)   throw new IOException();
                        BufferedReader bi1 = new BufferedReader(new FileReader(txt));
                        String explanationText = bi1.readLine();
                        String temp;
                        while((temp=bi1.readLine()) != null)
                            explanationText += ("\r\n" + temp);
                        bi1.close();
                        String explanationSrc = "";
                        if (mp3!=null)
                            explanationSrc = ossService.upload(FileUtil.fileToMultipartFile(mp3));
                        String expandFile = ossService.upload(FileUtil.fileToMultipartFile(file1));
                        CbExpandFileEntity cbExpandFile = new CbExpandFileEntity();
                        cbExpandFile.setForder(forder++);
                        cbExpandFile.setExpandFile(expandFile);
                        cbExpandFile.setExplanationSrc(explanationSrc);
                        cbExpandFile.setExplanationText(explanationText);
                        cbExpandFile.setRid(cbExpandResource.getId());

                        //如果是书法知识
                        if(expandEditionType == 2){
                            if (file2 == null)   throw new IOException();
                            String expandPpt = ossService.upload(FileUtil.fileToMultipartFile(file2));
                            cbExpandFile.setSfzsPpt(expandPpt);
                        }
                        expandFileService.save(cbExpandFile);
                    }
                }
            }
            srcFile.delete();
            deleteDirectory(destDirPath);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传文件的格式不正确！");
        }
        return R.ok();
    }

    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    public boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    public File multipartFileToFile(MultipartFile file){

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            try {
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return toFile;
    }

    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
